package lib;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class Monitor extends Actor{
	private ServerSocket mainSocket;
	private Socket client;
	boolean closing;

	public Monitor(ActorAddress superActor,ActorAddress myAddress) throws Exception{
		super(superActor,myAddress,"Monitor");
		mainSocket = new ServerSocket(2222);
		client = null;
		closing = false;
		System.out.println("You can connect by telnet to the TCP port 2222 to communicate with the system");
		startActor();
	}
	protected boolean standardRoutine() throws Exception{
		if(!closing) {
			if (client == null || client.isClosed())
				client = mainSocket.accept();

			BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));

			PrintStream clientOut = new PrintStream(client.getOutputStream());

			clientOut.println("Actor:");
			String actorType = reader.readLine();
			clientOut.println("Operation:");
			String operation = reader.readLine();
			clientOut.println("SuperOperation:");
			String superActorOperation = reader.readLine();
			clientOut.println("Message:");
			String message = reader.readLine();

			if (actorType.equals("SuperActor") && operation.equals("Terminate"))
				closing = true;

			//The monitor has a lot of privileges and can be considered as the superactor
			sendMsg(new Message(myAddress, "SuperActor", actorType.trim(), operation.trim(), superActorOperation.trim(), message.trim()));
		}
		
		return true;
	}
	protected boolean handleMessage(Message msg) throws Exception{
		if (msg.getOperation().equals("Terminate")) {
			System.out.println("Monitor will halt");
			client.close();
			return false;
		}
		return true;
	}
}

